<template>
  <div class='table-tree'>
    <table class="table" cellspacing="0" cellpadding="0" border="1">
      <thead class="table-header">
        <tr>
          <td v-for="(th, h) in column" :key="h">{{th.title}}</td>
        </tr>
      </thead>
      <tbody class="table-body" v-if="data.length === 0">
        <tr>
          <td :colspan="column.length">暂无数据</td>
        </tr>
      </tbody>
      <tbody class="table-body" v-else>
        <tr v-for="(tr, r) in data.length" :key="r" :class="{active: r === activeTR}" style="position:relative;">
          <td v-if="expand" @click="clickTR(data[r], r)">
            <span v-if="data[r].children"> + </span>
            <span v-else> - </span>
          </td>
          <td v-for="(td, key) in data[r].value" :key="key">
            <span>{{td}}</span>
          </td>
          <table-tree style="position:absolute;" v-if="data[r].children" :column="column" :data="data[r].children"></table-tree>
        </tr>
      </tbody>
      <tfoot class="table-footer" v-if="showPage">
        <tr>
          <td class="page" :colspan="column.length">共有{{data.length}}条数据</td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
export default {
  name: 'tableTree',
  props: {
    column: {
      type: Array,
      required: true,
      default: function () {
        return []
      }
    },
    data: {
      type: Array,
      default: function () {
        return []
      }
    },
    showPage: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      activeTR: null
    }
  },
  computed: {
    expand () {
      let result = false
      this.column.forEach(col => {
        if (col.key === 'expand') {
          result = true
        }
      })
      return result
    }
  },
  methods: {
    clickTR (tr, index) {
      console.log(tr)
      if (this.activeTR === index) {
        this.activeTR = null
      } else {
        this.activeTR = index
      }
    }

  }
}
</script>

<style scoped>
.table-tree * {
  box-sizing: border-box;
}
.table-tree {
  background: #ccc;
}

.table-tree .table {
  width: 100%;
  min-width: 200px;
  min-height: 100px;
  border-collapse:collapse;
}

.table td {
  min-height: 40px;
  min-width: 100px;
}

.table-body .active {
  background: #333;
  color: #fff;
}

.table-body tr {
  cursor: pointer;
}

.table-body tr:hover {
  background: #eee;
  color: #000;
}

.table-footer .page {
  text-align: right;
}
</style>
